#!/usr/bin/perl -w
use strict;
use Getopt::Long;

#the command line should be:  perl ripalign_analysis.pl 2010_4_26_17_57_49_ripalign.txt  -s sthe  for example
#right now this only works for ndis,cglo,ntet,smac,sther,tter except for ncra
open(DATA, "$ARGV[0]");


my @row;
my @idinfor;
my ($seqid,$sp,$chr,$st,);
my ($ca,$cc,$cg,$ct,$ca_dom);
my (@id,@species,@chrom,@start);
my @rec;
my $i=0;
my @matrix;

my $species;
GetOptions("species=s" => \$species);

while(<DATA>)
{ 
	next if /^Repeat/; #leave the head of the file out
	@row=split(/\s+/,$_);
	$seqid=$row[8];
	($ca,$cc,$cg,$ct) = ($row[41],$row[48],$row[55],$row[62]);
	@idinfor=split("_",$seqid);
	($sp,$chr,$st,)=($idinfor[0],$idinfor[2],$idinfor[3]);
	my $temp=$cc+$cg+$ct;
	if($temp==0){$ca_dom=$ca;} #make sure that it won't be divided by zero
	else {
	$ca_dom=$ca/($cc+$cg+$ct);  #calculate the CpA<->TpA dominance
	}
	if($sp eq $species) {
	$rec[$i++]=join "\t",$seqid,$sp,$chr,$st,$ca_dom;
  }
}   

#this is to store the table in a matrix for further sorting
for(my $j=1;$j <=scalar(@rec);$j++ )
{
	push @matrix,[$rec[$j]];
}


#this is to display the original matrix before sorting
foreach my $row ( @matrix) { 
        print join("\t",@$row),"\n";
}


#this is to sort the matrix by the start position, however it doesn't give error message:
#Use of uninitialized value in numeric comparison (<=>) 

foreach my $row (sort { scalar($b->[3] )<=> scalar($a->[3]) }
                @matrix) { 
        print join("\t",@$row),"\n";
}



